<template>
  <div class="app-container">
    <!-- MRP -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="计划状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择计划状态"
                class="!w-[192px]"
                filterable
                clearable
                @change="handleQuery"
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="计划编号" prop="code">
              <el-input
                v-noSpace
                v-model="queryParams.code"
                placeholder="请输入计划编号"
                clearable
                class="!w-[192px]"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="创建时间" prop="timeScopes">
              <el-date-picker
                v-model="queryParams.timeScopes"
                type="datetimerange"
                placeholder="选择创建时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
                @change="handleQuery"
              />
            </el-form-item>
            <el-row>
              <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
                <el-button v-hasPerm="'sys:planMrp:run'" @click="runPart({}, 'all')">
                  跑全部
                </el-button>
                <el-button v-hasPerm="'sys:planMrp:run'" @click="runPart({}, 'some')">
                  跑部份
                </el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </div>

        <el-card shadow="never">
          <el-table v-loading="loading" :data="pageData">
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column prop="code" label="计划编号" align="center" />
            <el-table-column prop="status" label="计划状态" align="center">
              <template #default="scope">
                <span :style="getStatusStyle(scope.row.status)">
                  {{ getStatusLabel(scope.row.status) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center">
              <template #default="scope">
                <span class="ellipsis" :title="scope.row.remark">
                  {{ displayedRemark(scope.row.remark) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="qty" label="订单数量" align="center">
              <template #default="scope">
                <span class="custom-label" @click="handleQty(scope.row, 'qty')">
                  {{ scope.row.qty }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="createName" label="创建人" align="center" />
            <el-table-column prop="prodDate" label="生产日期" align="center" />
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" fixed="right" width="250" align="center">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status == 1"
                  v-hasPerm="'sys:planMrp:force'"
                  type="primary"
                  link
                  size="small"
                  @click="forcePass(scope.row)"
                >
                  强制通过
                </el-button>
                <el-button
                  v-hasPerm="'sys:planMrp:rerun'"
                  v-if="scope.row.status == 1"
                  type="primary"
                  link
                  size="small"
                  @click="rerun(scope.row)"
                >
                  重跑
                </el-button>
                <el-button
                  v-if="
                    scope.row.status == '2' || scope.row.status == '3' || scope.row.status == '4'
                  "
                  type="primary"
                  size="small"
                  link
                  @click="viewDetail(scope.row)"
                >
                  查看
                </el-button>
                <el-button
                  type="danger"
                  v-hasPerm="'sys:planMrp:del'"
                  size="small"
                  link
                  @click="deletePlan(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 跑部分弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.type != 'all' ? '1200px' : '400px'"
      @close="handleCloseDialog"
    >
      <el-form
        v-if="dialog.type != 'qty' && dialog.type != 'all'"
        ref="dialogFormRef"
        :model="dialogParams"
        :inline="true"
      >
        <el-form-item label="订单编号" prop="code">
          <el-input
            v-noSpace
            v-model="dialogParams.code"
            placeholder="请输入订单编号"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleOrder"
          />
        </el-form-item>

        <el-form-item label="客户名称" prop="companyCode">
          <el-select
            v-model="dialogParams.companyCode"
            placeholder="请选择客户名称"
            clearable
            filterable
            class="!w-[192px]"
            @change="handleOrder"
            @visible-change="getName"
          >
            <el-option
              v-for="item in optionsName"
              :key="item.value"
              :label="item.label + item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="计划编号" prop="code">
          <el-input v-noSpace
            v-model="dialogParams.code"
            placeholder="请输入计划编号"
            clearable
            style="width: 200px"
            @keyup.enter="handleOrder"
          />
        </el-form-item> -->

        <el-form-item label="创建时间" prop="timeScopes">
          <el-date-picker
            v-model="dialogParams.timeScopes"
            type="datetimerange"
            placeholder="选择创建时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            @change="handleOrder"
          />
        </el-form-item>
        <el-row>
          <el-form-item>
            <el-button type="primary" icon="search" @click="handleOrder">搜索</el-button>
            <el-button icon="refresh" @click="handleResetOrder">重置</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <el-table
        v-if="dialog.type != 'all'"
        ref="multipleTable"
        :data="dialogData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column v-if="dialog.type != 'qty'" type="selection" width="55" />
        <el-table-column prop="code" label="订单编号" width="200" />
        <el-table-column prop="docType" label="订单类别" width="100">
          <template #default="scope">
            <span>
              {{ getDocTypeLabel(scope.row.docType) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="companyCode" label="客户编号" align="center" width="110" />
        <el-table-column prop="customerName" label="客户名称" align="center" width="160" />
        <el-table-column prop="contractCode" label="归属合同" align="center" width="110" />
        <el-table-column prop="salesMan" label="业务员" align="center" width="110">
          <template #default="scope">
            {{
              optionsSalesMan.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" width="190" />
        <el-table-column prop="deliveryDate" label="送货日期" align="center" width="110" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <span :style="{ color: getStatusColor(scope.row.status) }">
              {{ getStatus(scope.row.status) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
      </el-table>
      <pagination
        v-if="dialogTotal > 0"
        v-model:total="dialogTotal"
        v-model:page="dialogParams.pageNum"
        v-model:limit="dialogParams.pageSize"
        @pagination="handleOrder"
      />

      <template v-if="dialog.type != 'qty'">
        <div class="flex justify-right">
          <div>
            <div v-if="multipleSelection?.length || dialog.type == 'all'" class="df-fe">
              <p>请选择生产日期：</p>
              <el-date-picker
                v-model="prodDate"
                type="date"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
                clearable
              />
            </div>
            <p v-if="multipleSelection?.length || dialog.type == 'all'">
              备注：选中数据中最早送货日期
            </p>
          </div>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" v-if="dialog.type != 'qty'" @click="submitDialog">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import planMrpAPI, {
  planMrpPageQuery,
  rowMrpPageQuery,
  planMrpPageVO,
  planMrpDialogPageVO,
} from "@/api/planMrp/planMrp";
import configApi, { ConfigType } from "@/api/config/config";
import router from "@/router";
import UserAPI from "@/api/system/user";
defineOptions({
  name: "User",
  inheritAttrs: false,
});

const statusList = reactive([
  { label: "跑计划中", value: "0" },
  { label: "未通过", value: "1" },
  { label: "待确认", value: "2" },
  { label: "部分确认", value: "3" },
  { label: "确认完成", value: "4" },
]);

// 跑部分弹窗
const dialog = reactive({
  visible: false,
  title: "",
  type: "",
});

// 定义选中的行
const multipleSelection = ref([]);

const optionsName = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const queryFormRef = ref(ElForm);
const dialogFormRef = ref(ElForm);

const queryParams = reactive<planMrpPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const dialogParams = reactive<rowMrpPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const prodDate = ref("");

const pageData = ref<planMrpPageVO[]>();
const dialogData = ref<planMrpDialogPageVO[]>();
const total = ref(0);
const dialogTotal = ref(0);
const listTotal = ref(0);
const loading = ref(false);
let rowList = [];

//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const getProductName = () => {
  configApi.getConfigListByType(ConfigType.PROD_CODE).then((res) => {
    productList.value = res;
  });
};

// 查询
let intervalId: NodeJS.Timeout | null = null;

function handleQuery() {
  loading.value = true;
  console.log("queryParams", queryParams);

  planMrpAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      total.value = data.total;

      // 检查是否有状态为 0 的项
      const hasStatusZero = pageData.value?.some((item) => item.status == 0);

      if (hasStatusZero) {
        if (!intervalId) {
          intervalId = setInterval(() => {
            handleQuery();
          }, 2000);
        }
      } else {
        if (intervalId) {
          clearInterval(intervalId);
          intervalId = null;
        }
      }
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 弹窗查询订单列表
function handleOrder() {
  const params = { ...dialogParams };

  // console.log("params", params); params.codeList":["ORDER202501170000123,123"]
  if (dialog.type == "some") {
    params.mrpFlag = true;
  }
  planMrpAPI
    .getDialogPage(params)
    .then((data) => {
      dialogData.value = [...(data?.list as any)];
      dialogTotal.value = data.total;
    })
    .finally(() => {});
}

function handleOrderQty(row: any) {
  rowList = [];
  if (row) {
    if (row?.salesOrderCodes) {
      rowList = row.salesOrderCodes.split(","); // 将字符串拆分成数组
      dialogParams.codeList = rowList;
    }
  }
  handleOrder();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}

function handleResetOrder() {
  dialogFormRef.value.resetFields();
  dialogParams.pageNum = 1;
  dialogParams.code = undefined;
  dialogParams.customerName = undefined;
  dialogParams.timeScopes = undefined;
  dialogParams.companyCode = undefined;
  handleOrder();
}

onMounted(() => {
  handleQuery();
  // handleTotal();
  getSalesMan();
});

// 处理选中变化
function handleSelectionChange(selection: any) {
  if (selection?.length) {
    multipleSelection.value = selection;
    // 找出选中项中最早的交货日期
    const earliestDeliveryDate = selection.reduce((minDate: any, item: any) => {
      return new Date(item.deliveryDate) < new Date(minDate) ? item.deliveryDate : minDate;
    }, selection[0].deliveryDate);

    // 将最早的交货日期提前三天
    const dateBeforeThreeDays = new Date(earliestDeliveryDate);
    dateBeforeThreeDays.setDate(dateBeforeThreeDays.getDate() - 3);

    // 获取今天的日期
    const today = new Date();
    console.log(today, "today");
    console.log(dateBeforeThreeDays, "dateBeforeThreeDays");

    // 比较计算后的日期和今天的日期
    if (dateBeforeThreeDays < today) {
      prodDate.value = today.toISOString().split("T")[0];
    } else {
      prodDate.value = dateBeforeThreeDays.toISOString().split("T")[0];
    }
  }
}

// 根据状态返回标签
function getStatusLabel(status: number): string {
  switch (status) {
    case 0:
      return "跑计划中";
    case 1:
      return "未通过";
    case 2:
      return "待确认";
    case 3:
      return "部分确认";
    case 4:
      return "确认完成";
    default:
      return "未知状态";
  }
}

function getStatusStyle(status: number): string {
  switch (status) {
    case 1:
      return "color: red;";
    case 2:
      return "color: #5C4033;";
    case 3:
      return "color: green;";
    case 4:
      return "color: blue;";
    default:
      return "color: black;";
  }
}
// 跑部分弹窗
function runPart(row: any, type: any) {
  console.log("multipleSelection");
  dialog.visible = true;
  dialog.type = type;
  if (type == "qty") {
    dialog.title = "订单数量";
    handleOrderQty(row);
  } else if (type == "all") {
    dialog.title = "跑全部";
    dialogTotal.value = 0;
  } else {
    dialog.title = "跑部份";
    handleOrder();
  }

  multipleSelection.value = [];
}

function runAll() {
  planMrpAPI
    .runSomeMrp([])
    .then((data) => {
      ElMessage.success("跑全部成功");
      handleQuery();
    })
    .finally(() => {})
    .catch((err) => {
      ElMessage.error("跑全部失败");
    });
}

function handleCloseDialog() {
  dialog.visible = false;
  dialogParams.codeList = [];
}

// 提交弹窗
function submitDialog() {
  if (dialog.type != "all" && !multipleSelection.value?.length) {
    return ElMessage.error("请选择要跑的订单");
  }
  if (!prodDate) {
    return ElMessage.error("请选择生产日期");
  }
  const selectedCodes = multipleSelection.value.map((item: planMrpDialogPageVO) => item.code);
  planMrpAPI
    .runSomeMrp({ orderCodes: selectedCodes, prodDate: prodDate.value })
    .then((data) => {
      if (dialog.type == "all") {
        ElMessage.success("跑全部成功");
      } else if (dialog.type == "qty") {
        ElMessage.success("跑部分成功");
      }
      dialog.visible = false;
      handleQuery();
    })
    .finally(() => {})
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
}

// 强制通过
function forcePass(row: any) {
  ElMessageBox.confirm("确定强制通过该计划吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      planMrpAPI
        .forcePassPlan({ id: row?.id })
        .then(() => {
          ElMessage.success("强制通过成功");
          handleQuery(); // 刷新列表
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        });
    })
    .catch(() => {
      ElMessage.info("已取消");
    });
}

// 重新跑计划
function rerun(row: any) {
  ElMessageBox.confirm("确定重跑该计划吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      planMrpAPI
        .returnPlan({ id: row?.id })
        .then(() => {
          ElMessage.success("重跑成功");
          handleQuery(); // 刷新列表
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        });
    })
    .catch(() => {
      ElMessage.info("已取消");
    });
}

// 重新跑计划
function viewDetail(row: planMrpPageVO) {
  if (row?.status == 2 || row?.status == 3) {
    router.push({
      path: "/planManage/planOrderManage",
      query: {
        queryCode: row?.code,
      },
    });
  } else if (row?.status == 4) {
    router.push({
      path: "/prodManage/prodOrderManage",
      query: {
        queryCode: row?.code,
      },
    });
  }
}
//删除
function deletePlan(row: any) {
  ElMessageBox.confirm("确定要删除该计划吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      planMrpAPI
        .delPlan({ id: row?.id })
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery(); // 刷新列表
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

//备注
function displayedRemark(remark: any) {
  // 可以根据需要调整显示的字符数
  return remark?.length > 20 ? remark?.slice(0, 20) + "..." : remark;
}

const statusMap = {
  // 0: { label: "未提交", color: "purple" },
  0: { label: "待审核", color: "red" },
  1: { label: "审核拒绝", color: "gray" },
  2: { label: "已审核", color: "blue" },
  3: { label: "计划完成", color: "green" },
  4: { label: "生产完成", color: "cyan" },
  5: { label: "交付完成", color: "black" },
  // 7: { label: "取消订单", color: "orange" },
  // 8: { label: "取消待审核", color: "orange" },
};

function getStatus(status: number) {
  return statusMap[status as keyof typeof statusMap]?.label || "未知状态";
}

function getStatusColor(status: number) {
  return statusMap[status as keyof typeof statusMap]?.color || "未知状态";
}

const docTypeMap = {
  0: { label: "周期订单" },
  1: { label: "紧急订单" },
};

const optionsSalesMan = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const getSalesMan = () => {
  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    optionsSalesMan.value = data.list.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
  });
};

function getDocTypeLabel(status: number) {
  return docTypeMap[status as keyof typeof docTypeMap]?.label || "未知状态";
}
//点击数量
function handleQty(row: any, type: any) {
  runPart(row, type);
}

const getName = () => {
  planMrpAPI
    .getcusName({ pageNum: 1, pageSize: 999, isVendor: 0 })
    .then((data) => {
      optionsName.value = (data?.list || []).map((item: any) => ({
        value: item.companyCode,
        label: item.companyName,
        contractCode: item.code,
        contactPerson: item.contactInfo,
        contactPhone: item.contactPerson,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};

function changeName(val: any) {
  handleOrder();
}
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;

.ellipsis {
  max-width: 200px; /* 根据需要调整宽度 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.custom-label {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
</style>
